package com.yincheng.oms.bussiness.order.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.yincheng.oms.bussiness.order.Response;
import com.yincheng.oms.bussiness.order.entity.Order;
import com.yincheng.oms.bussiness.order.entity.OrderForm;
import com.yincheng.oms.bussiness.order.entity.OrderLog;
import com.yincheng.oms.bussiness.order.service.OrderService;

@Controller
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "/readPage.html", method = RequestMethod.GET)
	public ModelAndView readPage(ModelAndView view, String id) {
//		setView(view);
		
		OrderForm form = orderService.getOrderInfo(id);
		view.addObject("form",form);
		view.setViewName("/business/order/order-read");
		return view;
	}
	
	@RequestMapping(value = "/uploadOrders", method = RequestMethod.POST)
	@ResponseBody
	public Response uploadOrders(HttpServletRequest request,HttpServletResponse response){
		MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
		Response result = new Response(Response.SUCCESS);
		for (Map.Entry<String, MultipartFile> entry :  mRequest.getFileMap().entrySet()) {
			MultipartFile file = entry.getValue();
			try {
				result = orderService.uploadBatchOrders(file.getInputStream(), file.getOriginalFilename());
			}catch (DuplicateKeyException e) {
				result.setCode(Response.SERVER_ERROR);
				result.setMessage(e.getCause().getMessage());
				result.setErrorMessage(e.getMessage());
			}catch (Exception e) {
				result.setCode(Response.SERVER_ERROR);
				String message = e.getCause()==null ? e.getMessage() : e.getCause().getMessage();
				result.setMessage(message);
				result.setErrorMessage(e.getMessage());
			}
			
			continue;
		}
		return result;
	}
	
	@RequestMapping(value = "/addOrderLog", method = RequestMethod.POST)
	@ResponseBody
	public Response addOrderLog(OrderLog orderLog, Order order) throws Exception{
		Response result = orderService.addOrderLog(orderLog, order);
		return result;
	} 
}
